#!/bin/bash

echo "=== Testing Trim API endpoints ==="
echo

BASE_URL="http://localhost:8080"

# Function to test an endpoint
test_endpoint() {
    local method=$1
    local endpoint=$2
    local description=$3
    
    echo "📍 Testing: $description"
    echo "   $method $endpoint"
    
    if [ "$method" = "GET" ]; then
        response=$(curl -s "$BASE_URL$endpoint")
    else
        response=$(curl -s -X "$method" "$BASE_URL$endpoint")
    fi
    
    # Check response format
    if echo "$response" | grep -q '"code":' && echo "$response" | grep -q '"message":'; then
        # Standard API response format
        code=$(echo "$response" | jq -r '.code // "unknown"')
        message=$(echo "$response" | jq -r '.message // "unknown"')
        echo "   ✅ Status: $code - $message"
    elif echo "$response" | grep -q '"model_name":' && echo "$response" | grep -q '"trims":'; then
        # Get trims response format
        model_name=$(echo "$response" | jq -r '.model_name // "unknown"')
        total_trims=$(echo "$response" | jq -r '.total_trims // 0')
        message=$(echo "$response" | jq -r '.message // "Success"')
        echo "   ✅ Model: $model_name, Trims: $total_trims, $message"
    elif echo "$response" | grep -q '"error":'; then
        # Error response
        error=$(echo "$response" | jq -r '.error // "unknown error"')
        echo "   ❌ Error: $error"
    else
        echo "   ❌ Unexpected response format"
        echo "   Response: $(echo "$response" | head -c 100)..."
    fi
    echo
}

echo "🚀 Starting trim API tests..."
echo

# Test 1: Get trims without data (should return empty or instruction to scrape)
test_endpoint "GET" "/api/get_trims?model=Mustang" "Get trims for Mustang (should be empty)"

# Test 2: Scrape trims for Mustang
test_endpoint "POST" "/api/scrape_trims?model=Mustang" "Scrape trims for Mustang"

# Test 3: Get trims after scraping
test_endpoint "GET" "/api/get_trims?model=Mustang" "Get trims for Mustang (after scraping)"

# Test 4: Get existing Puma trims
test_endpoint "GET" "/api/get_trims?model=Puma" "Get trims for Puma (existing data)"

# Test 5: Test without model parameter
test_endpoint "GET" "/api/get_trims" "Get trims without model parameter (should error)"

echo "🎯 All tests completed!"
